import axios from 'axios'
import {updateToken} from '@/store/store'

axios.defaults.baseURL = 'http://localhost:8080'
/**
 * 创建axios实例
 * @type {AxiosInstance}
 */
const http = axios.create({
  // 后端请求url
  baseURL: 'http://localhost:8080',
  // 请求超时时间ms
  timeout: 5000,
})

/**
 * request拦截器
 * 在请求发送前做处理(比如加token、对请求参数做处理)
 */
http.interceptors.request.use(config => {
  // 每次请求前需要携带token
  let token = localStorage.getItem('accessToken')
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * response 拦截器
 * 在接口响应后做统一处理结果
 */
// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []
http.interceptors.response.use(
  response => {
    return response && response.data
  },
  async(error) => {
    const originalRequest = error.config
    let res = error.response
    if (res.data.code === 30002 && !originalRequest._retry) {
      originalRequest._retry = true
      if (!isRefreshing) {
        isRefreshing = true
        return await updateToken().then((res) => {
          const {accessToken, refreshToken, tokenExp, refreshTokenExp} = res.data.data
          localStorage.setItem("accessToken", accessToken)
          localStorage.setItem("refreshToken", refreshToken)
          localStorage.setItem("tokenExp", tokenExp)
          localStorage.setItem("refreshTokenExp", refreshTokenExp)

          // 执行队列中的请求
          requests.forEach(cb => cb())
          requests = []
          isRefreshing = false
          return http(originalRequest)
        }).catch(error => {
          localStorage.removeItem('accessToken')
          localStorage.removeItem('refreshToken')
          return Promise.reject(error)
        })
      } else {
        // 等待 token 更新完成后再发送请求
        return new Promise((resolve) => {
          requests.push(() => {
            originalRequest.headers.Authorization = `${localStorage.getItem('accessToken')}`
            resolve(http(originalRequest))
          })
        })
      }
    } else if (res.data.code === 401) {
      // 清除信息
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem("id")
      localStorage.removeItem("username")
      localStorage.removeItem("imageUrl")
    }
    return Promise.reject(error)
  }
)

export default http
